﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "组织架构-部门")]
public class SysOrgDeptApi : IDynamicApiController
{
    private readonly SysOrgDeptService _service;

    public SysOrgDeptApi(SysOrgDeptService service)
    {
        _service = service;
    }

    [QueryParameters]
    public async Task<dynamic> Get(string name, string pid)
    {
        var pp = XreqUtil.GetPp();
        var expable = Expressionable.Create<SysOrgDept>();
        if (!string.IsNullOrWhiteSpace(name))
        {
            expable.And(t => t.name.Contains(name.Trim()));
        }
        else
        {
            if (pid == "")
            {
                expable.And(t => t.pid == null);
            }
            else if (!string.IsNullOrWhiteSpace(pid))
            {
                expable.And(t => t.pid == pid);
            }
        }

        var items = await _service.repo.Context.Queryable<SysOrgDept>()
            .Where(expable.ToExpression())
            .OrderBy(u => u.ornum)
            .Select((t) => new {t.id, t.name, t.notes, t.crtim, t.uptim})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }

    // public List<Ztree> GetTree()
    // {
    //     var trees = _service.repo.Context.SqlQueryable<Ztree>("select id,pid,name from sys_org_dept where avtag=1 order by ornum")
    //         .ToTreeAsync(it => it.children, it => it.pid, null).Result;
    //     return trees;
    // }
    
    public List<SysOrgDeptVo> GetTree()
    {
        var trees = _service.repo.Context.SqlQueryable<SysOrgDeptVo>
                ("select id,pid,name,crtim,uptim,notes from sys_org_dept where avtag=1 order by ornum")
            .ToTreeAsync(it => it.children, it => it.pid, null).Result;
        return trees;
    }
    
    public async Task<SysOrgDept> GetOne(string id)
    {
        var sysOrgDept = await _service.SingleAsync(id);
        if (sysOrgDept.pid != null)
        {
            sysOrgDept.parent = await _service.repo.Context.Queryable<SysOrg>().InSingleAsync(sysOrgDept.pid);
        }
        return sysOrgDept;
    }

    public async Task<string> Post(SysOrgDept dept)
    {
        await _service.InsertAsync(dept);
        return dept.id;
    }

    public async Task<string> Put(SysOrgDept dept)
    {
        await _service.UpdateAsync(dept);
        return dept.id;
    }

    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        await _service.DeleteAsync(idArr);
    }
    
     /// <summary>
    /// 移动部门
    /// </summary>
    public async Task PostMove(TreeMovePo po)
    {
        await _service.PostMove(po);
    }
    
    
}